package java;

import net.sf.json.JSONObject;
import okhttp3.*;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

public class MD5 {

    private static String host = "http://rcsapi.wo.cn:8000/umcinterface/sendtempletmsg";

    public static void njn() {

        JSONObject json = new JSONObject();
        String cpcode = "AABEEF";
        String mobiles = "18827248807";
        String msg = "";
        String excode = "";
        String templetid = "64988";
        String key = "d5c3dc2a3f7dd350746291a848cfd045";
        //d5c3dc2a3f7dd350746291a848cfd045
        //f4930b8cb3a5e3293fcd209dc3a706f5
        String md5source = cpcode + msg + mobiles + excode + templetid + key;
        String print = cpcode + " " + msg + " "+ mobiles+ " " +excode + " " + templetid + " " + key;
        System.out.println("--签名串-" + print);
        String sign = "";
        try {
            sign = makeMD5(new String(md5source.getBytes("UTF-8"), "UTF-8")).toLowerCase();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        json.put("cpcode", cpcode);
        json.put("msg", msg);
        json.put("excode", excode);
        json.put("mobiles", mobiles);
        json.put("templetid", templetid);
        json.put("sign", sign);
        System.out.println("---sign---" + sign);
        System.out.println(postTest(json.toString()));

    }



    private static String postTest(String data){
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod("http://rcsapi.wo.cn:8000/umcinterface/sendtempletmsg");
        post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf8");// 在头文件中设置转码
        post.setRequestBody(data);

        try {
            client.executeMethod(post);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Header[] headers = post.getResponseHeaders();
        int statusCode = post.getStatusCode();
        for (Header h : headers) {
            System.out.println(h.toString());
        }
        String result = null;
        try {
            result = new String(post.getResponseBodyAsString().getBytes("gbk"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(result); // 打印返回消息状态
        post.releaseConnection();
        return result;
    }


    /*Response:封装了网络响应消息，比如响应消息头、缓存控制、响应消息体等。
    String content=response.body().string(); //获取字符串
    InputStream inputStream = response.body().byteStream();//获取字节流(比如下载文件)
    Callback回调是在子线程中执行的，如果要更新UI，请post到主线程中。*/
    public static String post(String data) {

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)//设置连接超时时间
                .readTimeout(60, TimeUnit.SECONDS)//设置读取超时时间
                .build();

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), data);
        Request req = new Request.Builder()
                .url(host)
                .post(requestBody)
                .build();

        Call call = okHttpClient.newCall(req);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //失败回调
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //成功回调，当前线程为子线程，如果需要更新UI，需要post到主线程中
                boolean successful = response.isSuccessful();
                //响应消息头
                Headers headers = response.headers();
                //响应消息体
                ResponseBody body = response.body();
//                String content=response.body().string();
                //缓存控制
                CacheControl cacheControl = response.cacheControl();
            }
        });
        return null;
    }


    public static String makeMD5(String plainText) {

        String re_md5 = new String();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes("UTF-8"));
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            re_md5 = buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return re_md5;
    }



}
